package org.xyl.game.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xyl.game.dto.UpdateCountRet;
import org.xyl.game.entity.Mygame;
import org.xyl.game.service.MyGameService;
import org.xyl.game.service.RoomService;
import org.xyl.game.tool.GsonUtil;
import org.xyl.game.tool.serializer.MygameSerializer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class GameController {

    @Autowired
    private MyGameService myGameService;

    @PostMapping("/start")
    @ResponseBody
    public String startGame(String roomid) {
        boolean b = myGameService.startGame(Integer.parseInt(roomid));
        Map<String, String> ansMap = new HashMap<>();
        ansMap.put("state", "success");
        return GsonUtil.getGsonBuilder().create().toJson(ansMap);
    }

    @PostMapping("/finish")
    @ResponseBody
    public String finishGame(String roomid, String username, String mycount, String result) {
        Map<String, String> ansMap = new HashMap<>();
        myGameService.finishGame(Integer.parseInt(roomid), username, Integer.parseInt(mycount), result);
        ansMap.put("state", "success");
        return GsonUtil.getGsonBuilder().create().toJson(ansMap);
    }

    @PostMapping("/history")
    @ResponseBody
    public String historyGame(String username) {
        Map<String, String> ansMap = new HashMap<>();
        List<Mygame> mygames = myGameService.historyGame(username);
        return GsonUtil.getGsonBuilder().registerTypeAdapter(Mygame.class, new MygameSerializer()).create().toJson(mygames);
    }

    @PostMapping("/updatecount")
    @ResponseBody
    public String updateCount(int roomid, String team, int count) {
        UpdateCountRet updateCountRet = myGameService.updateCount(roomid, team, count);

        return GsonUtil.getGsonBuilder().create().toJson(updateCountRet);
    }

}
